package com.ego.cart.service;

import com.ego.auth.entity.UserInfo;
import com.ego.cart.client.GoodsClient;
import com.ego.cart.interceptor.LoginInterceptor;
import com.ego.cart.pojo.Cart;
import com.ego.item.pojo.Sku;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    private static String KEY_PREFIX = "ego:cart:uid:";

    private ObjectMapper objectMapper = new ObjectMapper();


    public void addCart(Cart cart) {

        //获取登录的用户
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        String key = KEY_PREFIX + userInfo.getId();
        BoundHashOperations<String, Object, Object> hashOperations = this.stringRedisTemplate.boundHashOps(key);
        //判断下用户下面有没得购物车
        Long skuId = cart.getSkuId();
        if (hashOperations.hasKey(skuId.toString())) {//有的话
            //来对他做一个更新的操作
            String json = hashOperations.get(skuId.toString()).toString();
            try {
                Cart c = objectMapper.readValue(json, Cart.class);
                cart.setNum(cart.getNum() + c.getNum());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Sku sku = goodsClient.getSkuBySkuId(cart.getSkuId());
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
        }
        try {
            hashOperations.put(cart.getSkuId().toString(), objectMapper.writeValueAsString(cart));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public List<Cart> queryCartList(List<Cart> localCarts) {
        //判断下localStorage中有没得购物车
        //有的话和redis中的购物车合并
        if (localCarts != null && localCarts.size() > 0) {
            for (Cart cart :
                    localCarts) {
                this.addCart(cart);
            }
        }
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        String key = KEY_PREFIX + userInfo.getId();
        if (!this.stringRedisTemplate.hasKey(key)) {
            return null;
        }
        BoundHashOperations<String, Object, Object> hashOperations = this.stringRedisTemplate.boundHashOps(key);
        List<Object> carts = hashOperations.values();
        if (CollectionUtils.isEmpty(carts)) {
            return null;
        }
        return carts.stream().map(o -> {
            try {
                return objectMapper.readValue(o.toString(), Cart.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());
    }


    public void updateNum(Long skuId, Integer num) {
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        String key = KEY_PREFIX + userInfo.getId();
        BoundHashOperations<String, Object, Object> hashOperations = this.stringRedisTemplate.boundHashOps(key);
        //获取购物车
        String json = hashOperations.get(skuId.toString()).toString();
        Cart cart = null;
        try {
            cart = objectMapper.readValue(json, Cart.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        cart.setNum(num);
        //写入购物车
        try {
            hashOperations.put(skuId.toString(), objectMapper.writeValueAsString(cart));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public void deleteCart(String skuId) {
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        String key = KEY_PREFIX + userInfo.getId();
        BoundHashOperations<String, Object, Object> hashOperations = this.stringRedisTemplate.boundHashOps(key);
        //删除商品
        hashOperations.delete(skuId);
    }
}
